﻿namespace LUCAStudios.Silverlight.Controls
{
    using System;
    using System.Security.Cryptography;
    using System.Text;
    using Reg = System.Text.RegularExpressions;

    internal class IdenticonUtil
    {
        // Fields
        public static int Mask = -1;
        public static string Salt;

        // Methods
        public static int Code(string ipAddress)
        {
            if (ipAddress == default(string))
            {
                throw new ArgumentNullException("ipAddress", "Must specify a non-null ip address.");
            }
            if (Salt == default(string))
            {
                Salt = Environment.ProcessorCount.ToString();
            }
            byte[] addressBytes = GetAddressBytes(ipAddress);
            var builder = new StringBuilder();
            builder.Append((((((addressBytes[0] & 0xff) << 0x18) | ((addressBytes[1] & 0xff) << 0x10)) | ((addressBytes[2] & 0xff) << 8)) | (addressBytes[3] & 0xff)) & Mask);
            builder.Append('+');
            builder.Append(Salt);
            byte[] buffer2 = new SHA1Managed().ComputeHash(new UTF8Encoding().GetBytes(builder.ToString()));
            return (((((buffer2[0] & 0xff) << 0x18) | ((buffer2[1] & 0xff) << 0x10)) | ((buffer2[2] & 0xff) << 8)) | (buffer2[3] & 0xff));
        }

        public static string ETag(int code, int size)
        {
            return string.Concat(new object[] { "W/\"", Convert.ToString(code, 0x10), "@", size, "\"" });
        }

        private static byte[] GetAddressBytes(string ipAddress)
        {
            var buffer = new byte[4];
            if (!string.IsNullOrEmpty(ipAddress))
            {
                var input = Reg.Regex.Match(ipAddress, @"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}").ToString();
                var index = 0;
                foreach (var match in Reg.Regex.Matches(input, @"\d+"))
                {
                    byte.TryParse(match.ToString(), out buffer[index]);
                    index++;
                }
            }
            return buffer;
        }
    }
}
